/******************************************************************************
 * This file is part of libemb.
 *
 * libemb is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * libemb is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with libemb.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Project: Embedme
 * Author : FergusZeng
 * Email  : cblock@126.com
 * git	  : https://git.oschina.net/cblock/embedme
 * Copyright 2014~2020 @ ShenZhen ,China
*******************************************************************************/
#ifndef __TIMER_H__
#define __TIMER_H__

#include "BaseType.h"
#include "Thread.h"
#include "ThreadUtil.h"
#include <time.h>
#include <iostream>
#include <list>

namespace libemb{

/**
 *  \file   Timer.h   
 *  \class  TimerListener
 *  \brief  Timer定时器监听器接口	
 */
class TimerListener{
public:
    TimerListener(){};
    virtual ~TimerListener(){};
    virtual void onTimer(int timerID)=0;
};


/* 使用posix的rt库timer_create实现的定时器 */
class Timer{
public:
	Timer(TimerListener* listener,int timerID);
	~Timer();
	bool start(int msTimeout,bool repeat);
	void stop();
	int id(){return m_timerID;}
private:
	void reduce(int ms);
private:
	friend class TimerManager;
	TimerListener* m_listener{NULL};
	int m_timerID{0};
	int m_msInterval{0};
	int m_msTimeout{0};
	bool m_startFlag{false};
};


class TimerManager:public Singleton<TimerManager>{
	DECL_SINGLETON(TimerManager)
	{
	}
public:
	~TimerManager(){};
	bool initWithTick(int msTickInterval);
	bool registerTimer(std::shared_ptr<Timer> timer);      		/* 注册定时器 */
    bool unregisterTimer(std::shared_ptr<Timer> timer);		    /* 注销定时器 */	
private:
	void onTick();
	static void onSignal(int signo);
private:
	Mutex m_tmrlstMutex;
    std::list<std::shared_ptr<Timer>> m_timerList;
	timer_t m_baseTimer;
	int m_msTickInterval{100};
};

/**
 *  \file   Timer.h   
 *  \class  RTimer
 *  \brief  实时定时器类(每个定时器独占一个线程)
 */
class RTimer:public Runnable{
public:
    RTimer(const Thread& thread, const TimerListener& listener,int id);
    ~RTimer();
    bool start(int usTimeout,bool repeat=false);
    void stop();
    int id(){return m_timerID;}
private:
    void run();
private:
	Thread* m_thread{NULL};
	TimerListener* m_listener{NULL};
    bool m_startFlag{false};
	int m_timerID{0};
    int m_usInterval{0};
    int m_usTimeout{0};
};

}
#endif
